//
//  KPRegistViewController.swift
//  KPBaseProject
//
//  Created by 孑孓 on 2018/4/4.
//  Copyright © 2018年 Kipp. All rights reserved.
//

import UIKit
import Eureka

class KPRegistViewController: FormViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        createUI()
    }

    //MARK: -- 创建视图
    func createUI() {
        self.title = "注册"
        view.backgroundColor = UIColor.white

        form +++ Section()
        <<< PhoneRow() { row in
            row.tag = "phoneRow"
            row.title = "手机号"
            row.placeholder = "请输入手机号"
        }
        <<< PasswordRow() { row in
            row.tag = "passwordRow"
            row.title = "密码"
            row.placeholder = "请输入密码"
        }
        <<< IntRow() { row in
            row.tag = "codeRow"
            row.title = "验证码"
            row.placeholder = "请输入验证码"
        }

        let problemBtn = UIBarButtonItem.init(title: "找回密码", style: UIBarButtonItemStyle.plain, target: self, action: #selector(findPasswordBtnClick(btn:)))
        navigationItem.rightBarButtonItem = problemBtn

        let codeBtn = UIButton.init(type: .custom)
        codeBtn.frame = CGRect.init(x: 20, y: Screen.height - 200, width: Screen.width - 40, height: 40)
        codeBtn.setTitle("获取验证码", for: .normal)
        codeBtn.backgroundColor = UIColor.cyan
        codeBtn.addTarget(self, action: #selector(codeBtnClick(btn:)), for: UIControlEvents.touchUpInside)
        view.addSubview(codeBtn)

        let registBtn = UIButton.init(type: .custom)
        registBtn.frame = CGRect.init(x: 20, y: Screen.height - 120, width: Screen.width - 40, height: 40)
        registBtn.setTitle("注册", for: .normal)
        registBtn.backgroundColor = UIColor.yellow
        registBtn.addTarget(self, action: #selector(registBtnClick(btn:)), for: UIControlEvents.touchUpInside)
        view.addSubview(registBtn)

    }

    // MARK: - Action
    @objc func registBtnClick(btn: UIButton) {
        let dic = form.values(includeHidden: true)
        let phoneStr = dic["phoneRow"] as! String
        let passwordStr = dic["passwordRow"] as! String
        let codeStr = dic["codeRow"] as! String

        if phoneStr.isEmpty {

        } else if passwordStr.isEmpty {

        } else if codeStr.isEmpty {

        } else {
            registRequest(phone: phoneStr, password: passwordStr, msgCode: codeStr)
        }
    }

    @objc func codeBtnClick(btn: UIButton) {
        let dic = form.values(includeHidden: true)
        let phoneStr = dic["phoneRow"] as! String
        if phoneStr.isEmpty {
            
        }else{
            getTimeRequest(phone: phoneStr, msgType: "register")
        }
    }

    @objc func findPasswordBtnClick(btn: UIButton) {
        let vc = KPFindPasswordViewController()
        self.navigationController?.pushViewController(vc)
    }
    
    // MARK: NetworkRequest
    // MARK: -- 获取服务器时间戳
    fileprivate func getTimeRequest(phone: String, msgType: String){
        Api.getJSONRequest(ApiType.获取服务器当前时间戳, parameters: ["phone":phone])
        .mapBaseModel()
            .subscribe(onNext: { (model) in
                KPLog("返回状态码：\(model.resultState)---返回请求结果：\(model.msg)---返回数据\(String(describing: model.data!))")
                if model.resultState == 1 {
                    let time = model.data!.string
                    let secretMd5 = phone + time! + "_demo"
                    //获取验证码
                    self.getCodeRequest(phone: phone, secret: secretMd5, msgType: msgType)
                }else{
                    //请求失败
                }
            }, onError: { (error) in
                KPLog("错误---\(error)")
            })
            .disposed(by: bag)
    }

    // MARK: -- 获取验证码
    fileprivate func getCodeRequest(phone :String, secret :String, msgType :String) {
        Api.getJSONRequest(ApiType.获取验证码, parameters: ["phone":phone, "secret":secret.MD5(), "msgType":msgType])
        .mapBaseModel()
            .subscribe(onNext: { (model) in
                KPLog("返回状态码：\(model.resultState)---返回请求结果：\(model.msg)---返回数据\(String(describing: model.data))")
                if model.resultState == 1{
                    KPLog("获取验证码成功")
                }else{
                    KPLog("获取验证码失败")
                }
            }, onError: { (error) in
            })
        .disposed(by: bag)
    }

    // MARK: -- 开始注册
    fileprivate func registRequest(phone: String, password: String, msgCode: String) {
        Api.postJSONRequest(ApiType.注册, parameters: ["account": phone, "password": password, "msgCode": msgCode])
            .mapBaseModel()
            .subscribe(onNext: { (model) in
                
                KPLog("返回状态码：\(model.resultState)---返回请求结果：\(model.msg)---返回数据\(String(describing: model.data!))")
            }, onError: { (error) in
            })
            .disposed(by: bag)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
